<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/swfobject/2.1/swfobject.js" type="text/javascript"></script>
    <script src="http://www.google.com/jsapi" type="text/javascript"></script>
    <script src=" https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="js/jquery-ui-1.8.9.custom.min.js"></script>
    <script type="text/javascript" src="js/jquery.form.js"></script> 
    <script src="/js/gu.js" type="text/jscript"></script>

    <link type="text/css" href="css/sunny/jquery-ui-1.8.9.custom.css" rel="stylesheet" /> 
 


	<script>
		//global varialbes
		player = null;
		last_clicked_index_in_summary = 0;			
		synced_text = []; //Structure : row : 0 = char value, row : 1 = synced time stamp, 2 = system time
		text = "";
		
		function printSynced_text(){
			res = "";
			for(var i = 0; i<synced_text.length; i++){
				res = res + synced_text[i][0];
			}
			//res = res + "#";
			return res;
		}
		function checkStringDiff(s1,s2){
			var l1 = s1.length,
		    	l2 = s2.length,
		    	CS = -1,
		    	S1_CE = l1,
		    	S2_CE = l2,
		    	new_string ="";
		    
		    for(var i = 0; i<l1; i++){
		        if ( i == l2 )
		            break;
		        if ( s1[i] == s2[i] )
		            CS = CS + 1;
		        else break; 
		    }    
		    for(var i = 0; i<l1; i++){
		    	if ( ( S1_CE - 1 == CS ) || ( S2_CE == CS ) )
		    		break;
		        if ( S2_CE == 0 )
		            break;
		        if ( s1[S1_CE-1] == s2[S2_CE-1] ){ 
		            S1_CE = S1_CE - 1;
		            S2_CE = S2_CE - 1;
		        }    
		        else break;
			}   
			if ( S2_CE - CS > 1 ) new_string = s2.slice(CS+1,S2_CE);  //slice(beg,end) but actualy end-1
			return [CS,S1_CE,new_string];
		}
		
		function getSyncTimeByIndex(index){
			if (( index >=0 ) && ( index < synced_text.length ) && (synced_text.length > 0)){
				return synced_text[index][1];
			}
			else {
				//$("#Error").text("getSyncTimeByIndex)Error With Index - "+index.toString());
				alert("(getSyncTimeByIndex)Error With Index - "+index.toString())	;
				return 0;
			}
		}
		
		function updateSyncTextTime(change_start,change_end,change_new_text,new_time){
			var a = [], b = [];
			if ( change_start != -1 ) a = synced_text.slice(0,change_start);
			for (var i = 0; i<change_new_text.length; i++){
				a.push([change_new_text[i],new_time, getCurrentTimeStamp()]);
			}
			if ( change_end != text.length ) b = synced_text.slice(change_end+1,synced_text.length+1);
			synced_text = a;
			synced_text = synced_text.concat(b);
		}
		
		function getCurrentTimeStamp(){
			return player.getCurrentTime();
		}
		
		function syncText(summery_text){
			var res = [],
				CS = 0,
				S1_CE = 0,
				l1 = text.length,
				l2 = summery_text.length,
				change_new_text = "";
				
			res = checkStringDiff(text,summery_text);
			CS = res[0];
			S1_CE = res[1];
			change_new_text = res[2];
			
			if ( S1_CE > CS ){ 
				if ( S1_CE == l1 ){ //change is at the end
					//TODO add check that there are spaces or irrelevant text on the right
					updateSyncTextTime( CS+1, l1, change_new_text, getCurrentTimeStamp());
				}
				else if ( CS == -1 ) { //change is at the start
					updateSyncTextTime( -1, -1, change_new_text, getSyncTimeByIndex(0));
				}
				else updateSyncTextTime( CS + 1 , S1_CE - 1, change_new_text, getSyncTimeByIndex(S1_CE - 1));
		
			}
			
			//TODO speed this line up by just inserting the new chars
			text = summery_text;
		}
		
		function jumpToSelectedPoint(){
			var index = last_clicked_index_in_summary;
			if ( index >= synced_text.length ) index = synced_text.length-1;
			if (( synced_text.length > 0 ) && ( player != null ) && ( synced_text[index][1] >= 0 ))
				player.seekTo(synced_text[index][1],true);
			//alert("Jump To Index :"+index+"   Time : "+ synced_text[index][1]);
		}
		
		function getSummaryFromServer(youtubeId){
			ajax("GET","string-summary-get","youtubeId="+youtubeId,
				function(json){
					synced_text = JSON.parse(json);
					$("#summary").attr("value",printSynced_text());
				})
		}
	    
	    
	    //----------------------------------YouTube-----------------------------------
		function loadYouTubePlayer(video_ID, HTML_element_ID, width, height, isC){
			var params = { allowScriptAccess: "always" };
			var atts = { id: HTML_element_ID };
			var vUrl = "http://www.youtube.com/e/"+video_ID+"?enablejsapi=1&version=3&playerapiid=ytplayer";	  
			swfobject.embedSWF(vUrl,HTML_element_ID, width, height, "8", null, null, params, atts);
		} 		
		
		//Automatic call back of YouTube API after Player Loads on screen
		function onYouTubePlayerReady(playerId) {
			//global variable player
			player = document.getElementById("vid"); 
			if ( player != null )
				setInterval('$("#VideoTime").attr("value","Time : "+player.getCurrentTime())',250);

		} 
		
		function changeVideo(video_ID, start_seconds, start_imidiatly){
			//TODO check about the quality
			if (( video_ID != null ) && ( video_ID != "" )){
				player.cueVideoById(video_ID,start_seconds,"default");
				if ( start_imidiatly )
					player.playVideo();
			}
		}	
		function getYouTubeMovieID(){
			return "yt_"+player.getVideoUrl().slice("http://www.youtube.com/watch?v=".length,"http://www.youtube.com/watch?v=".length+11);
		}
	    //--------------------------END---YouTube---END----------------------------		
	$(function(){	    
		loadYouTubePlayer("wwrLZ9j3t_M","vid",425,350,false);

		$("#summary").keyup(function(event){
			syncText($(this).attr("value")); //sync summery 
			//$("#text").text(printSynced_text()); //show synced text
		})
	    
	    
	    ///
	    $("#summary").click(function(event){
			var index = getCaret(this);
			if ( index >= synced_text.length ) index = synced_text.length-1;
			if ( synced_text.length > 0 ) 
				$("#SyncTime").attr("value","["+synced_text[index][0]+"] - "+synced_text[index][1]);
	    });
	    // save the last clicked index on the summary text box
	    $("#summary").click(function(event){
			last_clicked_index_in_summary = getCaret(this);
	    });
	});
	</script>
</head>
<body>

	<input type="button" onClick='ajax2("POST","summary-save","youtubeId="+"yt_"+getYouTubeMovieID()+"&json="+JSON.stringify(synced_text))' value="Save">
	<input type="button" onClick='getSummaryFromServer("yt_"+getYouTubeMovieID())' value="Load">
	<input type="button" onClick="jumpToSelectedPoint()" value="Jump">
	<textarea id="VideoID" rows="1" cols="15">wwrLZ9j3t_M</textarea>
	<input type="button" onClick="changeVideo($('#VideoID').attr('value'),0,false);" value="Load Video"></br>
	<textarea id="SyncTime" rows="1" cols="20"></textarea>
	<textarea id="VideoTime" rows="1" cols="20">Time : 0</textarea></br>
	<textarea id="summary" rows="18" cols="80"></textarea>
		
	<div id="vid"></div>
</body>
